/**
 * Created by no1 on 2015/8/28.
 */
'use strict';
var mysql = require('../mysql.js');
var C = require('../../config/index');
var F = require('../../common/function');
var MPosts = require('../../model/posts.js');
var MTags = require('../../model/tags.js');
var MUser = require('../../model/users.js');
var Mman = require('../../common/man.js');
var imgRule = require('../../common/imgRule.js');
var _ = require('underscore');
var _s = require('underscore.string');
var md5 = require('md5');
var request = require('koa-request');
var async_request = require('request');
var logstash = require('./../logFlow/logstash.js');
var mark = require('../mark.js');
_.v = require('validator');

/*
 *@todo  API18 主题列表
 * */
exports.getPostList = function*(Env, data) {
  let loginStatus = Env.I.loginStatus;
  var fields;
  if (!data) {
    fields = Env.I;
  } else {
    fields = data;
  }
  var version = parseInt(fields.apiVerNum);
  var act = fields.act;
  var page = fields.page || 1;
  var pageSize = fields.pagesize != undefined ? parseInt(fields.pagesize) : C.threadlist.pageSize;
  var beginIndex = (page - 1) * pageSize;
  var lastId = fields.lastid;
  var threads;
  var vestId = fields.vestId || 0;

  // 初始化 pgmark
  let pgmark = mark.addMark(null, 'PG', act);

  var returnData = {
    pageIndex: page,
    lastid: 0,
    items: []
  };
  // tsoft: 0 最新，1 回帖最多
  var tsort = fields.tsort || 0;
  var manager = fields.manager;
  if ((act == 1) && !(manager && manager == 1 && F.isManager(loginStatus.groupid))) {//最新帖子qie
    //threads=yield F.list(0,beginIndex,pageSize,lastId);
    //以当天零点时间为基准
    var zerotime = F.getzeroSeconds();
    if (tsort == 0) { // 最新
      var threadData = yield mysql.query('SELECT t.tid FROM mh_thread t where t.status = 1 ORDER BY lastpost DESC LIMIT ?,?', [beginIndex, pageSize]);
    } else if (tsort == 1) {
      // 一周内最热回帖
      var threadData = yield mysql.query('SELECT t.tid FROM mh_thread t where t.status = 1 AND t.digest = 1  AND  t.lastpost>=? ORDER BY t.replies DESC LIMIT ?,?', [zerotime, beginIndex, pageSize]);
    } else if (tsort == 2) {
      // 一周内最热被看
      var threadData = yield mysql.query('SELECT t.tid FROM mh_thread t where t.status = 1 AND t.lastpost>=? AND t.sharetimes>0 ORDER BY t.views DESC LIMIT ?,?', [zerotime, beginIndex, pageSize]);
    } else if (tsort == 3) {
      // 一周内分享最多的帖子
      var threadData = yield mysql.query('SELECT t.tid FROM mh_thread t where t.status = 1 AND t.lastpost>=? AND t.sharetimes>0 ORDER BY t.sharetimes DESC LIMIT ?,?', [zerotime, beginIndex, pageSize]);
    }

    if (threadData.length == 0) {
      return F.returnMsg(300, '已没有数据了', 3);
    }
    // 取得tid列表结束
    var tidArr = [];
    for (var i in threadData) {
      tidArr.push(threadData[i].tid);
    }
    var aid = C.threadup.newest;
    if (aid > 0) {
      var sliderData = yield mysql.query('SELECT tid FROM mh_thread WHERE tid=(SELECT id FROM mh_slider WHERE aid=? AND sstype=6 AND type=3) AND status=1', [aid]);
      if (sliderData.length > 0 && parseInt(sliderData[0].tid) > 0 && page == 1 && tsort == 0) {
        tidArr.unshift(sliderData[0].tid);//把帖子推进第一条
      }
      if (sliderData.length > 0) {
        for (var i in tidArr) {//如果发现后面有帖子就删除
          if (i > 0 && tidArr[i] == sliderData[0].tid) {
            tidArr.splice(i, 1);
          }
        }
      }
    }
    threads = yield F.returnThreadInfo(tidArr);
  } else if ((act == 9) && !(manager && manager == 1 && F.isManager(loginStatus.groupid))) {//好友发帖
    var uid = -1;//-1 拿某人发帖，但是没登录，此时只能拿到管理员的帖子
    if (fields.tokenkey != undefined) {//没传tokenkey 拿管理员发帖，有传要验证身份
      if (!loginStatus.status) {
        return F.returnMsg(401, '登录用户才能查看好友的发帖', 3);
      }
      uid = parseInt(loginStatus.uid);
    }
    pgmark = mark.addMark(pgmark, 'A', uid);
    threads = yield F.list(uid, beginIndex, pageSize, lastId);
  } else {//其他帖子列表
    var addField = "";//管理员的话加多个字段
    var statusWhere = 'AND t.status = 1 ';
    if(loginStatus.status){
      statusWhere = 'AND (t.status = 1 OR (t.status = 2 and t.uid='+loginStatus.uid+')) ';
    }

    // 仅不是管理模式，并且act=1/5时才插播
    var spotsEnable = false;
    if (manager != 1 && (act == 1 || act == 5)) {
      spotsEnable = true;
    }

    if (manager && manager == 1 && F.isManager(loginStatus.groupid)) {
      statusWhere = '';
      addField += 't.status,';
    }
    /*
     if(version==1){//版本1时还没有标签坐标
     var sql = 'SELECT t.tid,t.pid,t.uid,u.nickname,u.face,t.timeline,t.replies,t.liketimes,p.imgext,pc.post,t.closed,t.digest,'+addField+
     'GROUP_CONCAT(tt.tagsid) as tagsid,GROUP_CONCAT(IFNULL(tg.tagtitle,"")) as tagstitle '+
     'FROM mh_thread t '+
     'LEFT JOIN mh_user u ON u.uid = t.uid '+
     'LEFT JOIN mh_post p ON p.pid = t.pid '+
     'LEFT JOIN mh_post_content pc ON pc.pid = t.pid '+
     'LEFT JOIN mh_thread_tags tt ON tt.tid = t.tid '+
     'LEFT JOIN mh_tags tg ON tg.tagid = tt.tagsid '+
     'WHERE 1=1 '+' myWhere '+ statusWhere+
     'GROUP BY t.tid '+
     'ORDER BY t.tid DESC ';
     }else{
     var sql = 'SELECT t.tid,t.pid,t.uid,u.nickname,u.face,t.timeline,t.replies,t.liketimes,p.imgext,pc.post,t.closed,'+addField+'t.digest '+
     'FROM mh_thread t '+
     'LEFT JOIN mh_user u ON u.uid = t.uid '+
     'LEFT JOIN mh_post p ON p.pid = t.pid '+
     'LEFT JOIN mh_post_content pc ON pc.pid = t.pid '+
     'WHERE 1=1 '+' myWhere '+ statusWhere+
     'GROUP BY t.tid '+
     'ORDER BY t.tid DESC ';
     }*/

    if (act == 1) { // 最新帖子
      var threadData = yield mysql.query('SELECT t.tid FROM mh_thread t where 1=1 ' + statusWhere + ' ORDER BY tid DESC LIMIT ?,?', [beginIndex, pageSize]);
    } else if (act == 2) {  // 按某标签方式
      var tagid = fields.tagid;
      if (tagid == undefined || tagid == '') {
        return F.returnMsg(400, '请输入标签ID', 1);
      }

      pgmark = mark.addMark(pgmark, 'T', tagid);

      var poiid = fields.poiid;
      if (poiid && poiid.length > 0) {
        var threadData = yield mysql.query('SELECT DISTINCT t.tid FROM mh_thread t INNER JOIN mh_thread_tags tt2 ON tt2.tid = t.tid WHERE tt2.tagsid=? AND (tt2.tagstype=4 AND tt2.poiid=?) ' + statusWhere + ' ORDER BY t.lastpost DESC LIMIT ?,?', [parseInt(tagid), poiid, beginIndex, pageSize]);
      } else {
        var threadData = yield mysql.query('SELECT DISTINCT t.tid FROM mh_thread t INNER JOIN mh_thread_tags tt2 ON tt2.tid = t.tid WHERE tt2.tagsid=? AND (tt2.tagstype=1 OR tt2.tagstype=4 OR tt2.tagstype=5 OR tt2.tagstype=6 OR tt2.tagstype=99) ' + statusWhere + ' ORDER BY t.lastpost DESC LIMIT ?,?', [parseInt(tagid), beginIndex, pageSize]);
      }
    } else if (act == 3) {  // 按某人发主题帖方式
      var uid = fields.uid;
      if (loginStatus.status && (uid == undefined || uid == loginStatus.uid)) {
        uid = loginStatus.uid;
        statusWhere = 'AND t.status in(1,2) ';
      }
      if (uid == undefined || uid == '') {
        return F.returnMsg(400, '请输入用户ID', 1);
      }
      pgmark = mark.addMark(pgmark, 'A', uid);
      var sstype = fields.sstype;//帖子类型 1 为日志帖
      var addWhere = '';
      var fieldVal = [parseInt(uid), beginIndex, pageSize];
      if (sstype) {
        addWhere += 'AND type=? ';
        fieldVal = [parseInt(uid), parseInt(sstype), beginIndex, pageSize];
      }
      var threadData = yield mysql.query('SELECT t.tid FROM mh_thread t WHERE t.uid=? ' + addWhere + statusWhere + ' ORDER BY t.tid DESC LIMIT ?,?', fieldVal);
    } else if (act == 4) {  // 按自己收藏的主题帖方式
      if (!loginStatus.status) {
        return F.returnMsg(401, '登录用户才能查看收藏主题帖', 3);
      }
      pgmark = mark.addMark(pgmark, 'A', loginStatus.uid);
      var threadData = yield mysql.query('SELECT f.tid FROM mh_fav f LEFT JOIN mh_thread t ON f.tid=t.tid WHERE f.uid=? ' + statusWhere + ' ORDER BY f.timeline DESC LIMIT ?,?', [parseInt(loginStatus.uid), beginIndex, pageSize]);
    } else if (act == 16) {//按某人关注的帖子类别
      if (!loginStatus.status) {
        return F.returnMsg(401, '登录用户才能查看自己订阅的主题列表', 3);
      }
      //有关注类别时显示关注类别，没有时显示全部
      var myPinCategory = yield mysql.query('select cid from mh_pincategory mp where mp.uid=?', [parseInt(loginStatus.uid)]);
      if (myPinCategory.length > 0) {
        var categoryStr = 0;
        for (var i in myPinCategory) {
          categoryStr = categoryStr == 0 ? myPinCategory[i]['cid'] : categoryStr + ',' + myPinCategory[i]['cid'];
        }
        var threadData = yield mysql.query('select DISTINCT t.tid from mh_thread t where t.cid IN (' + categoryStr + ') ' + statusWhere + ' ORDER BY t.tid DESC LIMIT ?,?', [beginIndex, pageSize]);
      } else {
        var threadData = yield mysql.query('SELECT t.tid FROM mh_thread t where 1=1 ' + statusWhere + ' ORDER BY tid DESC LIMIT ?,?', [beginIndex, pageSize]);
      }
    } else if (act == 17) {//按某帖子类别方式获取帖子
      var cid = fields.cid;
      if ((cid == undefined || cid == '') && act == 17) {
        return F.returnMsg(400, '请输入帖子类别ID', 1);
      }
      var threadData = yield mysql.query('SELECT t.tid from mh_thread t where t.cid=? ' + statusWhere + 'ORDER BY tid DESC LIMIT ?,?', [cid, beginIndex, pageSize]);
      if (loginStatus.status && threadData.length > 0) {
        mysql.query('INSERT into mh_threadCatogory_viewlog(uid,timeline,cid,page) VALUES(?,UNIX_TIMESTAMP(),?,?)', [loginStatus.uid, cid, page]);
      }
    }
    else if (act == 5) {  // 按自己订阅的标签显示主题帖
      if (!loginStatus.status) {
        return F.returnMsg(401, '登录用户才能查看自己订阅标签的主题列表', 3);
      }
      //有订阅时显示订阅，没订阅时显示全部
      pgmark = mark.addMark(pgmark, 'A', loginStatus.uid);
      var myPinTag = yield mysql.query('SELECT mp.tagid FROM mh_pintag mp WHERE mp.uid=?', [parseInt(loginStatus.uid)]);
      if (myPinTag.length > 0) {
        var tagidStr = 0;
        for (var i in myPinTag) {
          tagidStr = tagidStr == 0 ? myPinTag[i]['tagid'] : tagidStr + ',' + myPinTag[i]['tagid'];
        }
        var threadData = yield mysql.query('SELECT  DISTINCT mtt.tid FROM mh_thread_tags mtt left join mh_thread t on mtt.tid=t.tid WHERE mtt.tagsid IN (' + tagidStr + ') ' + statusWhere + ' ORDER BY mtt.tid DESC LIMIT ?,?', [beginIndex, pageSize]);
      } else {
        var threadData = yield mysql.query('SELECT t.tid FROM mh_thread t where 1=1 ' + statusWhere + ' ORDER BY tid DESC LIMIT ?,?', [beginIndex, pageSize]);
      }
    } else if (act == 6 || act == 18) {  // 按某人发主题帖及回帖方式  后台调用
      if (!(loginStatus.status == true && F.isManager(loginStatus.groupid))) {
        return F.returnMsg(401, '权限验证失败', 1);
      }
      var uid = fields.uid;
      var sql = '';
      var valArr = [beginIndex, pageSize];
      if (act == 6) {
        if (uid != undefined && parseInt(uid) > 0) {
          sql = "SELECT mp.tid,mp.pid,mp.`status`,mpc.post,mp.imgext,mp.first,mu.uid,mu.nickname,mp.timeline FROM mh_post mp INNER JOIN mh_post_content mpc ON mp.pid=mpc.pid inner JOIN mh_user mu on mu.uid=mp.uid WHERE mp.uid=? ORDER BY mp.pid DESC limit ?,?";
          valArr = [parseInt(uid), beginIndex, pageSize];
        } else {
          sql = "SELECT mp.tid,mp.pid,mp.`status`,mpc.post,mp.imgext,mp.first,mu.uid,mu.nickname,mp.timeline FROM mh_post mp INNER JOIN mh_post_content mpc ON mp.pid=mpc.pid inner join mh_user mu on mu.uid=mp.uid ORDER BY mp.pid DESC limit ?,?";
        }
      } else if (act == 18) {
        sql += 'SELECT DISTINCT * from ( ' +
          ' SELECT mdi.tid,mpc.pid,mp.`status`,mpc.post,mp.imgext,mp.`first`,mu.uid,mu.nickname,mdi.type_id,mp.timeline,mvp.uid AS notify_uid,mt.timeline as threadtime' +
          ' FROM mh_dynamic_info mdi ' +
          'INNER JOIN mh_thread mt on mt.tid=mdi.tid ' +
          ' INNER JOIN mh_post mp ON mp.pid = mdi.pid ' +
          ' INNER JOIN mh_post_content mpc ON mpc.pid = mdi.pid ' +
          ' INNER JOIN mh_user mu on mu.uid=mdi.authorid ' +
          ' LEFT JOIN mh_vest_post mvp ON mvp.tid = mdi.tid AND mvp.vid = mdi.uid ' +
          ' WHERE mdi.a_ismanager = 0 and 	mdi.type_id = 2 and mdi.u_isvest=1 ';
        if (parseInt(vestId) > 0) {
          sql += ' AND mvp.uid = ?  and mp.uid<> ? ';
          valArr.unshift(vestId, vestId);
        }
        sql += ' GROUP BY mdi.pid ' +
          ' UNION ALL' +
          ' SELECT mdi.tid,mdi.pid,mt.`status`,mpc.post,mp.imgext,mp.`first`,mu.uid,mu.nickname,mdi.type_id,mp.timeline,mdi.uid as notify_uid,mt.timeline as threadtime from mh_dynamic_info mdi' +
          ' inner join mh_user mu on mu.uid =mdi.authorid' +
          ' inner join mh_thread mt on mt.tid=mdi.tid' +
          ' inner join mh_post mp on mp.tid=mt.tid and mp.`first`=1 inner join mh_post_content mpc on mpc.pid=mp.pid where mdi.a_ismanager=0 and mdi.type_id=5 and mdi.u_isvest=1';
        if (parseInt(vestId) > 0) {
          sql += ' and mdi.uid=? ';
          valArr.unshift(vestId);
        }
        sql += ')A where A.threadtime>unix_timestamp(date_add(NOW(), interval -1 month)) order by A.pid DESC limit ?,?';
      }
      var threads = yield mysql.query(sql, valArr);
      for (var i in threads) {
        var thread = threads[i];
        var tempThreadData = yield F.returnThreadInfo([thread.tid]);
        if (version < 3) {//版本3之前，帖子只有一张图
          thread.img = F.generateAttachmentUrl(thread.pid, thread.imgext);//帖子图片
        } else {
          var imgIdArr = [];
          if (!_.isEmpty(tempThreadData[0].validimg)) {
            imgIdArr = tempThreadData[0].validimg.split(',');
          }
          var imgArr = [];
          if (!_.isEmpty(tempThreadData[0].imagestring)) {
            var imgStrArr = tempThreadData[0].imagestring.split(',');
          }
          for (var j in imgIdArr) {
            var tempData = imgIdArr[j].split('-');
            var imgUrl = '';
            if (manager && manager == 1 && F.isManager(loginStatus.groupid)) {//后台并且是管理员
              //imgUrl = F.generateAttachmentUrl(thread.pid, thread.imgext, 0, tempData[0]);
              imgUrl = imgStrArr == undefined ? '' : imgRule.str2imgURI(imgStrArr[j])[0].imgURI + C.upyun.suffix;
              imgArr.push({imgindex: parseInt(tempData[0]), url: imgUrl, status: parseInt(tempData[1])});
            } else {
              if (tempData[1] == 1) {//有效图片
                //imgUrl = F.generateAttachmentUrl(thread.pid, thread.imgext, 0, tempData[0]);
                imgUrl = imgStrArr == undefined ? '' : imgRule.str2imgURI(imgStrArr[j])[0].imgURI + C.upyun.suffix;
                imgArr.push({imgindex: parseInt(tempData[0]), url: imgUrl});
              }
            }
          }
          thread.img = imgArr;//帖子图片
          thread.imgcount = 0;
          if (thread.imgext != '') {
            thread.imgcount = parseInt(tempThreadData[0].imgcount);
          }
        }
        delete thread.imgext;
      }
      returnData.items = threads;
      return F.returnMsg(200, '列表返回成功', 3, returnData);
    } else if (act == 7) {//精华贴子（推荐页面）
      //var threadData=yield mysql.query('SELECT t.tid FROM mh_thread t where 1=1 and t.digest=1 '+statusWhere+' ORDER BY tid DESC LIMIT ?,?',[beginIndex, pageSize]);
      //取 10000 条 存入Redis
      //var threadData=yield mysql.query('SELECT tid FROM mh_thread mt WHERE mt. STATUS = 1 AND mt.digest = 1 ORDER BY IF (mt.timeline > (UNIX_TIMESTAMP() - 259200),IF (mt.userreplies > 50,50,mt.userreplies)*2+IF (mt.views > 100, 100, mt.views) * 0.5+IF (vest > 0, 0, 30)+IF (mt.sharetimes > 5,5,mt.sharetimes) * 5+IF (mt.toptimeline >UNIX_TIMESTAMP() ,100,0)+ mt.timeline * 0.0005 - UNIX_TIMESTAMP() * 0.0005 + 300,0)  DESC, mt.lastpost DESC LIMIT ?,?',[beginIndex, pageSize]);

      threadData = yield F.getDigestList(page, pageSize);
      var aid = C.threadup.recommend;
      if (aid > 0) {
        var sliderData = yield mysql.query('SELECT tid FROM mh_thread mt WHERE tid=(SELECT id FROM mh_slider WHERE aid=? AND sstype=6 AND type=3) AND status=1', [aid]);
        if (sliderData.length > 0 && parseInt(sliderData[0].tid) > 0 && page == 1) {
          threadData.unshift({"tid": sliderData[0].tid});//把帖子推进第一条
        }
        if (sliderData.length > 0) {
          for (var i in threadData) {//如果发现后面有帖子就删除
            if (i > 0 && threadData[i].tid == sliderData[0].tid) {
              threadData.splice(i, 1);
            }
          }
        }
      }
    } else if (act == 8) { //同原API19 返回主题帖信息 相同
      var tid = fields.tid;
      var threadData = [];
      if (loginStatus.status && (uid == undefined || uid == loginStatus.uid)) {
        uid = loginStatus.uid;
        statusWhere = 'OR (t.status =2 and t.uid=' + uid + ') ';
      }
      if (tid) {
        var tmpThreadData = yield mysql.query('SELECT t.tid FROM mh_thread t where 1=1 AND tid=? ' + statusWhere + ' ORDER BY tid DESC', [tid]);
        if (tmpThreadData.length > 0) {
          threadData[0] = [];
          threadData[0].tid = tid;
        }
      }
    } else if (act == 10) {//回帖被投诉未处理
      if (!(loginStatus.status == true && F.isManager(loginStatus.groupid))) {
        return F.returnMsg(401, '权限验证失败', 1);
      }
      var sql = "SELECT mp.tid,mp.pid,mp.`status`,mpc.post,mp.imgext,mp.first FROM mh_post mp INNER JOIN mh_post_content mpc ON mp.pid=mpc.pid where mp.pid in(SELECT DISTINCT pid FROM mh_post_complain WHERE `status`=0)  ORDER BY mp.pid DESC limit ?,?";
      var valArr = [beginIndex, pageSize];
      var threads = yield mysql.query(sql, valArr);
      for (var i in threads) {
        var thread = threads[i];
        var tempThreadData = yield F.returnThreadInfo([thread.tid]);
        if (version < 3) {//版本3之前，帖子只有一张图
          thread.img = F.generateAttachmentUrl(thread.pid, thread.imgext);//帖子图片
        } else {
          var imgIdArr = tempThreadData[0].validimg.split(',');
          var imgArr = [];
          for (var j in imgIdArr) {
            var tempData = imgIdArr[j].split('-');
            var imgUrl = imgRule.str2imgURI(tempThreadData[0].imagestring.split(',')[0])[0].imgURI + C.upyun.suffix_min;
            if (manager && manager == 1 && F.isManager(loginStatus.groupid)) {//后台并且是管理员
              //imgUrl = F.generateAttachmentUrl(thread.pid, thread.imgext, 0, tempData[0]);
              imgArr.push({imgindex: parseInt(tempData[0]), url: imgUrl, status: parseInt(tempData[1])});
            } else {
              if (tempData[1] == 1) {//有效图片
                //imgUrl = F.generateAttachmentUrl(thread.pid, thread.imgext, 0, tempData[0]);
                imgArr.push({imgindex: parseInt(tempData[0]), url: imgUrl});
              }
            }
          }
          thread.img = imgArr;//帖子图片
          thread.imgcount = 0;
          if (thread.imgext != '') {
            thread.imgcount = parseInt(tempThreadData[0].imgcount);
          }
        }
        delete thread.imgext;
      }
      returnData.items = threads;
      return F.returnMsg(200, '列表返回成功', 3, returnData);
    } else if (act == 11) {//整型日志帖
      let uid = fields.uid;
      if (uid != undefined && _.v.isInt(uid) && parseInt(uid) > 0) {
        var threadData = yield mysql.query('SELECT t.tid FROM mh_thread t INNER JOIN mh_thread_extend mte ON t.tid=mte.tid where t.type>0 and t.uid=? ' + statusWhere + ' ORDER BY t.lastmodified DESC LIMIT ?,?', [uid, beginIndex, pageSize]);
      } else {
        var threadData = yield mysql.query('SELECT t.tid FROM mh_thread t INNER JOIN mh_thread_extend mte ON t.tid=mte.tid where t.type>0 ' + statusWhere + ' ORDER BY t.lastmodified DESC LIMIT ?,?', [beginIndex, pageSize]);
      }
    } else if (act == 12) {//按某个整形日志帖
      var tid = fields.tid;
      if (!tid) {
        return F.returnMsg(400, '帖子id参数有误', 1);
      }
      var threadData = yield mysql.query('SELECT t.tid FROM mh_thread t WHERE t.tid=? OR t.fid=? ' + statusWhere + ' ORDER BY t.tid DESC LIMIT ?,?', [tid, tid, beginIndex, pageSize]);
      //if(threadData.length>0){
      //  threadData.unshift({tid:tid});
      //}
    } else if (act == 13) {//取登录用户发的日志帖项目
      if (!loginStatus.status) {
        return F.returnMsg(401, '登录用户才能操作', 3);
      }
      var threadData = yield mysql.query('SELECT t.tid FROM mh_thread t LEFT JOIN mh_thread_extend mte ON t.tid=mte.tid WHERE t.uid=? and t.type>0 ' + statusWhere + '  ORDER BY t.tid DESC LIMIT ?,?', [parseInt(loginStatus.uid), beginIndex, pageSize]);
    } else if (act == 14) { // 发现页面

      //取轮播
      var retData = yield F.getSliderNew({title: '', stid: 7, app_ver_arr: fields.app_ver_arr});
      if (!_.isEmpty(retData)) {
        returnData.items.push(retData);
      }

      //取达人
      retData = yield F.getLatestTalent({type: 3, title: '达人', more: 1});
      if (!_.isEmpty(retData)) {
        returnData.items.push(retData);
      }
      //取专题
      //more:2
      //if (C.env != 'production'){
      if (fields.app_ver_arr.code >= 25) { // 新专题
        retData = yield F.getSliderNew({
          title: '专题',
          stid: 13,
          more: 0,
          moreTitle: '往期回顾',
          limit: 4,
          app_ver_arr: fields.app_ver_arr
        });
        if (!_.isEmpty(retData)) {
          returnData.items.push(retData);
        }
      } else { //旧专题
        retData = yield F.getSliderNew({
          title: '专题',
          stid: 12,
          more: 0,
          moreTitle: '往期回顾',
          limit: 4,
          app_ver_arr: fields.app_ver_arr
        });
        if (!_.isEmpty(retData)) {
          returnData.items.push(retData);
        }
      }
      /*
       //取帖子类别
       let categorys_group=yield F.redisCo.get(C.redisPre.env_categorysgroup);
       let cg=[];
       if(categorys_group!=null &&categorys_group.length>0){//如果在redis中存在
       cg=F.isJson(categorys_group);
       }else{
       //cg=yield F.
       }*/

      //取推荐标签
      if (C.slider_faxian_tags.length > 0) {
        let tags_group = yield F.redisCo.get(C.redisPre.env_tagsgroup);
        let sg = [];
        if (tags_group != null && tags_group.length > 0) { // 如果已经在redis中存在
          sg = F.isJson(tags_group);
        } else {
          sg = yield F.getSliderGroup(C.slider_faxian_tags);
          yield F.redisCo.set(C.redisPre.env_tagsgroup, JSON.stringify(sg));
        }

        // 取所有标签tagid
        let tagsArr = [];
        for (let i in sg) {
          if (!_.isEmpty(sg[i].items)) {
            if (loginStatus.status == true) {
              for (let j in sg[i].items) {
                tagsArr.push(sg[i]['items'][j].tagid);
              }
            }
          }
        }

        if (loginStatus.status == true) {
          var tagnew = yield F.getUserTagnew({uid: loginStatus.uid, tagid: tagsArr});
        }

        // 设置新帖数
        for (let i in sg) {
          if (!_.isEmpty(sg[i].items)) {
            if (loginStatus.status == true) {
              for (let j in sg[i].items) {
                sg[i]['items'][j]['tagnew'] = tagnew['tagid_' + sg[i]['items'][j].tagid];
              }
            }
            returnData.items.push(sg[i]);
          }
        }
      }

      return F.returnMsg(200, '列表返回成功', 3, returnData);
    } else if (act == 15) {//专题列表type=7
      //取专题
      var retData = [];
      if (C.env != 'production') {
        retData = yield F.getSliderNew({title: '', stid: 12, app_ver_arr: fields.app_ver_arr});
        if (!_.isEmpty(retData)) {
          returnData.items.push(retData);
        }
      }
      if (_.isEmpty(retData) && page > 1) {
        return F.returnMsg(300, '已没有数据了', 3);
      }
      return F.returnMsg(200, '列表返回成功', 3, returnData);
    } else if (act == 19) {//按某个项目标签获取美容日记贴列表
      let tagsid = fields.tagsid || '';
      if (tagsid == '' || !_.v.isInt(tagsid)) {
        return F.returnMsg(400, '传入的tagsid无效', 3);
      }
      var threadData = yield mysql.query('SELECT mtt.tid from mh_thread_tags mtt INNER JOIN mh_thread mt on mt.tid=mtt.tid INNER JOIN mh_thread_extend mte on mte.tid=mt.tid ' +
        'where mtt.tagstype=6 and mtt.tagsid=? and mt.status=1 ORDER BY mte.lastUpdate DESC LIMIT ?,?', [tagsid, beginIndex, pageSize]);
    }

    //add by 2015.12.15
    /*
    if (_.v.isIn(act, [7])) {
      if(page ==1 &&(fields.app_ver_arr && fields.app_ver_arr.code && fields.app_ver_arr.code < 50)){
        if(fields.app_ver_arr){
          var retData = yield F.getSliderNew({title: '', stid: 14, app_ver_arr: fields.app_ver_arr});
          if (!_.isEmpty(retData)) {
            returnData.items.push(retData);
          }
        }
        if(fields.app_ver_arr && fields.app_ver_arr.code && fields.app_ver_arr.code >48){
            returnData.items = yield F.spots(1, returnData.items, {
              act: fields.act,
              page:page,
              app_ver_arr: fields.app_ver_arr
            });
        }
      }
    }
*/
    // 首页、第一页、且  menu=0时：插播推荐的人、帖子、标签等。
    //或 推荐页(精华)第一页、且 menu=0时：插播推荐的人、帖子、标签等。

    let code_version = fields.app_ver_arr.code || 0;
    if (_.v.isIn(act, [1, 7, 20])) {
      if ((fields.app_ver_arr && fields.app_ver_arr.code && fields.app_ver_arr.code < 50 && fields.app_ver_arr.os == 1) || (act == 20 && code_version>=50)) {
        let obj_config = {
          act: act,
          page: page,
          menu: fields.menu,
          version: version,
          env: C.env,
          manager: manager,
          env_app_ver_arr: Env.app_ver_arr,
          code: fields.app_ver_arr.code,
          fields_app_ver_arr: fields.app_ver_arr,
          latest_code: 50
        };
        returnData.items = yield F.getHotInformation(obj_config);
        if (act == 20) {
          if (returnData.items && returnData.items.length > 0) {
            return F.returnMsg(200, '热点信息返回成功', 3, returnData);
          } else {
            return F.returnMsg(300, '已没有数据了', 3);
          }
        }
      }
    }
    /*2015.12.15 由于安卓没实现单独调API20，先将API20全部返回空数组
    if (act == 20) {
      //let obj_config={act:act,page:page,menu:fields.menu,version:version,env:C.env,manager:manager,env_app_ver_arr:Env.app_ver_arr,code:fields.app_ver_arr.code,fields_app_ver_arr:fields.app_ver_arr};
      //returnData.items=yield F.getHotInformation(obj_config);
      //if(returnData.items.length>0){
      //  return F.returnMsg(200, '热点信息返回成功', 3, returnData);
      //}else{
      //  return F.returnMsg(300, '已没有数据了', 3);
      //}
     return {};
    }*/
    // 处理完 act=? 判断

    if (threadData && threadData.length == 0) {
      if (page <= 1) {//第一页时不提示没有数据
        return F.returnMsg(300, '已没有数据了', 3);
      } else {
        return F.returnMsg(300, '已没有数据了', 3);
      }
    }
    // 取得tid列表结束
    var tidArr = [];
    if (threadData && threadData.length > 0) {
      for (var i in threadData) {
        tidArr.push(threadData[i].tid);
      }
    }
    var dailyThread = [];
    if (act == 12 && page == 1) {//当拿帖子列表第一页时（包括封面贴），分两次获取，第一次获取日记标题贴，第二次获取剩下的
      if (tidArr.length > 0) {
        dailyThread = yield F.returnThreadInfo(tid);
      }
    }
    threads = yield F.returnThreadInfo(tidArr);
    if (dailyThread.length > 0) {
      threads.unshift(dailyThread[0]);
    }
  }
  if (!threads || threads.length <= 0) {
    if (page <= 1) {//第一页时不提示没有数据
      return F.returnMsg(300, '已没有数据了', 3);
    } else {
      return F.returnMsg(300, '已没有数据了', 3);
    }
  }
  if (act == 8 && !(manager && manager == 1 && F.isManager(loginStatus.groupid)) && threads[0].status == 0) {
    return F.returnMsg(400, '无效帖子', 1);
  }

  // 如果已登录，获取我的所有好友、所有收藏帖
  var myFriends;
  var myFav;
  var myLiked;
  if (loginStatus.status) {
    // 好友
    myFriends = yield F.userList(parseInt(loginStatus.uid), 2);
//    收藏帖
    myFav = yield F.userList(parseInt(loginStatus.uid), 3);
    //    点赞帖
    myLiked = yield F.userList(parseInt(loginStatus.uid), 4);
  }

  ////过滤无对比图日志贴
  //let showValidThread=false;
  //if(_.v.isIn(act,[12,13])){
  //  if(loginStatus.uid==threads[0].uid||(manager && manager == 1 && F.isManager(loginStatus.groupid))){
  //    showValidThread=true;
  //  }
  //}
  //if(!showValidThread){
  //  threads = _.filter(threads, function (thread) {
  //    return thread.imgCompareValid>0;
  //  });
  //}

  var threadsLen = threads.length;
  var nowTime = F.timestamp();
  if (threadsLen > 0) {

    /*
     //取马甲uid
     let vestUidList=[];
     if (manager && manager == 1&& F.isManager(loginStatus.groupid)){
     let vestTmp = yield mysql.query('SELECT uid FROM mh_vest');
     for(let i in vestTmp){
     vestUidList.push(vestTmp[i].uid);
     }
     }
     */
    for (var i = threadsLen - 1; i >= 0; i--) {
      var thread = threads[i];
      //tempTid=thread.tid;
      if (!(manager && manager == 1 && F.isManager(loginStatus.groupid))) {
        if (thread.status == 0 && thread.timeline > nowTime - 300) {//不返回最近5分钟的无效的数据
          threads.splice(i, 1);
          continue;
        }
      }
      thread.type = 1;
      if (thread.imgcount == 0) {
        thread.type = 2;
      }
      if (thread.ttype > 0) {
        if (thread.fid == 0) {
          if (!(act == 12 && i == threadsLen - 1)) {
            thread.type = 15;//有关联商品的日记帖
            if (thread.ttype == 2) {
              thread.type = 19;//无关联商品的日记帖
            }
          }
        }
      }
      thread.friend = false;
      thread.fav = false;
      thread.like = false;

      //过滤掉管理类别的ctype;
      //if(act!=8 && manager && manager==1 &&  F.isManager(loginStatus.groupid)){
      //  if(_.v.isIn(thread.cid,C.threadCategory.SPAM_thread_array)){
      //    console.log('tid is :'+thread.tid+'  '+thread.isVest+' cid is '+thread.cid);
      //    delete thread.ctype;
      //  }
      //}

      /*
       // 如果是管理人员，返回vest=1,否则返回0
       if (manager && manager == 1&& F.isManager(loginStatus.groupid)) {
       if(_.v.isIn(thread.uid,vestUidList)){
       thread.isVest=1;
       }else{
       thread.isVest=0;
       }
       }
       */
      // 是否已经关注该用户
      if (myFriends && thread.uid) {
        if (_.contains(myFriends, thread.uid.toString())) {
          thread.friend = true;
        }
      }
      // 是否收藏了帖子
      if (myFav && thread.tid) {
        if (_.contains(myFav, thread.tid.toString())) {
          thread.fav = true;
        }
      }
      // 是否点赞
      if (myLiked && thread.pid) {
        if (_.contains(myLiked, thread.pid.toString())) {
          thread.like = true;
        }
      }
      // 帖子标签
      switch (version) {
        case 1://版本1
          var tags = JSON.parse(thread.tags);
          thread.tags = [];
          for (let i in tags) {
            if (tags[i].tagsType == 1) {
              thread.tags.push({tagid: tags[i].tagsid, tagtitle: tags[i].tagstitle});
            }
          }
          thread.img = F.generateAttachmentUrl(thread.pid, thread.imgext);//帖子图片
          delete thread.likeusers;
          break;
        case 2:
        case 3:
        case 4:
          if (version < 4 || (version == 4 && act == 8)) {
            if (thread.likeusers) {
              thread.likeusers = JSON.parse(thread.likeusers);
            }
            for (var k in thread.likeusers) {
              thread.likeusers[k].faceUrl = F.generateFaceUrl(parseInt(thread.likeusers[k].face), parseInt(thread.likeusers[k].uid));
              delete thread.likeusers[k].face;
            }
          } else {//版本4开始不是拿帖子详情不返回点赞用户
            delete thread.likeusers;
          }
          if (thread.tags) {//全部图片的标签
            var tags = JSON.parse(thread.tags);
          }
          thread.tags = tags;
          if (version == 2) {
            thread.img = F.generateAttachmentUrl(thread.pid, thread.imgext);//帖子图片
          } else if (version > 2) {
            if (thread.validimg) {
              var imgIdArr = thread.validimg.split(',');
            }
            if (thread.imagestring) {
              var imgStrArr = thread.imagestring.split(',');
            }
            var imgArr = [];//买个图片的标签
            var desc = '';//每张图的描述
            var imgTags = [];
            if (thread.imgcount == 0 || thread.validimg == '' || thread.imagestring == '') {//无图模式,或网络原因导致img数组为空
              for (var j in tags) {
                if (tags[j].tagsType != 6) {
                  delete tags[j].imgindex;
                  delete tags[j].x;
                  delete tags[j].y;
                  delete tags[j].placeLeft;
                  // 帖子类型 并且是android  code<24时，或 ios code<3时不处理
                  if (tags[j].tagsType == 3 && ((fields.app_ver_arr.code < 24 && fields.app_ver_arr.os == 1) || (fields.app_ver_arr.code < 3 && fields.app_ver_arr.os == 2))) {
                    //delete tags[j];
                  } else {
                    imgTags.push(tags[j]);
                  }
                }
              }
              if (thread.ttype != 2) {//非关联商品美容贴，关联商品美容贴的tags在item下面
                imgArr.push({tags: imgTags});
              }
            } else {
              for (var j in imgIdArr) {
                var tempData = imgIdArr[j].split('-');
                var imgUrl = '';
                imgTags = [];
                if (manager && manager == 1 && F.isManager(loginStatus.groupid)) {//后台并且是管理员
                  //imgUrl = F.generateAttachmentUrl(thread.pid, thread.imgext, 0, tempData[0]);
                  imgUrl = imgStrArr == undefined ? '' : imgRule.str2imgURI(imgStrArr[j])[0].imgURI + C.upyun.suffix;
                  for (var j in tags) {
                    if ((tags[j].imgindex == tempData[0]) && tags[j].tagsType != 6) {
                      delete tags[j].imgindex;
                      imgTags.push(tags[j]);
                    }
                  }
                  if (thread.imgdesc != '') {
                    var tmp = JSON.parse(thread.imgdesc);
                    var descArr = tmp.desc;
                    desc = descArr[parseInt(tempData[0])];
                  }
                  imgArr.push({
                    imgindex: parseInt(tempData[0]),
                    url: imgUrl,
                    tags: imgTags,
                    desc: desc,
                    status: parseInt(tempData[1])
                  });
                } else {
                  if (tempData[1] == 1) {//有效图片
                    //imgUrl = F.generateAttachmentUrl(thread.pid, thread.imgext, 0, tempData[0]);
                    imgUrl = imgRule.str2imgURI(imgStrArr[j])[0].imgURI + C.upyun.suffix;
                    for (var j in tags) {
                      if ((tags[j].imgindex == tempData[0]) && tags[j].tagsType != 6) {
                        delete tags[j].imgindex;
                        // 帖子类型 并且是android  code<24时，或 ios code<3时不处理
                        if (tags[j].tagsType == 3 && ((fields.app_ver_arr.code < 24 && fields.app_ver_arr.os == 1) || (fields.app_ver_arr.code < 3 && fields.app_ver_arr.os == 2))) {
                          //delete tags[j];
                        } else {
                          imgTags.push(tags[j]);
                        }
                      }
                    }
                    if (thread.imgdesc) {
                      var tmp = JSON.parse(thread.imgdesc);
                      var descArr = tmp.desc;
                      desc = descArr[parseInt(tempData[0])];
                    }
                    imgArr.push({
                      imgindex: parseInt(tempData[0]),
                      url: imgUrl,
                      tags: imgTags,
                      desc: desc
                    });
                  }
                }
              }
            }
            thread.img = imgArr;//帖子图片
            if (thread.ttype != 2) {//非关联商品美容贴，关联商品美容贴的tags在item下面
              delete thread.tags;
            }
          }
          break;
        default:
          break;
      }
      //返回视频或者普通H5页面信息
      var youkuClient = C.youku.client_id;
      var youkuAndriodHeight = C.youku.android_height;
      var youkuIOSHeight = C.youku.ios_height;
      if (thread.video && thread.video.length > 12) {
        if (act == 8) {//当按取主题帖时（帖子详细信息时，才返回所有视频信息，否则只返回h5type跟videoimg）
          thread.video = {
            android_height: youkuAndriodHeight,
            ios_height: youkuIOSHeight,
            videourl: F.generateVideoURL(thread.video),
            //videoimg: F.generateAttachmentUrl(thread.pid, 'screenshot', 2, 'video')//视频截图
            videoimg: imgRule.str2imgURI(imgRule.id2imgStr('P', thread.pid, 'jpg', 'video'))[0].imgURI + C.upyun.video_screenshot_suffix
          };
        }
        else {
          thread.video = {
            //videoimg: F.generateAttachmentUrl(thread.pid, 'play', 2, 'video')//视频截图
            videoimg: imgRule.str2imgURI(imgRule.id2imgStr('P', thread.pid, 'jpg', 'video'))[0].imgURI + C.upyun.video_play_suffix
          };
        }
      } else {
        delete thread.video;
      }
      // 节选前95字符的主题内容
      if (thread.post && thread.post.length > 0 && act != 8 && thread.vip != 1) {
        thread.post = thread.post.substring(0, 95);
      }
      thread.mark = mark.addMark(mark.addMark(pgmark, 'TH', thread.tid), 'O', beginIndex + i + 1);
      thread.faceUrl = F.generateFaceUrl(thread.face, thread.uid);
      thread.imgcount = parseInt(thread.imgcount);
      if (thread.postusers) {
        thread.postusers = JSON.parse(thread.postusers);
      }
      // 删除多余项
//    delete thread.likeusers;
      delete thread.imagestring;
      delete thread.imgext;
      delete thread.face;
      delete thread.tagsid;
//      delete thread.pid;
      delete thread.tagtitle;
      //  delete thread.imgcount;
      delete thread.validimg;
      delete thread.imgdesc;

      if (thread.ttype > 0) {//整形帖
        delete thread.postusers;
        delete thread.ttype;
      }
      if ((act == 1) && !(manager && manager == 1 && F.isManager(loginStatus.groupid))) {
        delete thread.views;
        delete thread.favtimes;
        delete thread.sharetimes;
      }
    }
  }

  if (act == 8 && !(manager && manager == 1) && !F.isManager(loginStatus.groupid)) {//取主题帖时数据库里帖子浏览数+1，帖子缓存浏览数+1  后台查看不计算
    yield MPosts.editThread('views=views+1', 'tid=?', [tid]);//更新贴子浏览次数

    // logstash 流程
    var json = {
      uid: loginStatus.uid,
      tid: tid,
      action: 'view'
    };
    logstash.article(json);

    //更新帖子信息开始
    var key = C.redisPre.thread_info;
    key = _s.sprintf(key, parseInt(tid));
    var temp = yield F.redisCo.EXISTS(key);
    if (temp == 1) {
      F.redisClient.HINCRBY(key, 'views', 1);//帖子被浏览数+1
    }
    //更新帖子类别查看记录
    mysql.query('update mh_thread_category mtc inner join mh_thread mt on mtc.cid=mt.cid ' +
      'set mtc.views=mtc.views+1 where mt.tid=?', [tid]);
    //更新帖子信息结束
    if (loginStatus.status) {
      mysql.query('INSERT INTO mh_thread_viewlog(uid,timeline,tid,cid) SELECT ?,UNIX_TIMESTAMP(),tid,cid from mh_thread where tid=?', [parseInt(loginStatus.uid), tid]);
    }
    //delete thread.postusers;
  }
  if (threads.length > 0) {
    returnData.lastid = threads[threads.length - 1].tid;
  }
  else {
    returnData.lastid = 0;
  }
//  returnData.items = threads;

  /*
   //推荐页面顶端添加送面膜活动 page=1时
   if (C.env != 'production') {
   if (act == 7 && page == 1) {
   //2 推荐页主菜单
   if (fields.app_ver_arr.code > 26) {
   returnData.items.push({
   type: 9,
   imgUrl: C.upyun.img_url + '/activity/banner_1.jpg',
   actid: 1,
   acttype: 1, // 到屈臣氏店面领取
   android_height: 63,
   ios_height: 56
   }
   );
   }
   // 推送o2o入口
   if (fields.app_ver_arr.code > 29) {
   returnData.items.push({
   type: 14,
   imgUrl: C.upyun.img_url + '/activity/o2o.jpg',
   //actid: 1,
   //acttype: 1, // o2o入口
   android_height: 63,
   ios_height: 56
   }
   );
   }
   }
   }

   if ((act == 1 && page == 1 && fields.menu != 0 && version < 3) || (act == 7 && page == 1 && fields.menu != 0)) {
   //returnData.items = yield F.spots(threads, pageSize, page, C.spotsRules);
   //1 h5 主菜单
   returnData.items = yield F.spots(1, returnData.items, {act: act, page: page, app_ver_arr: Env.app_ver_arr});
   }

   //取达人 增时段控制： act=7 推荐页  & 9-12 18-22点
   if (C.env != 'production' && manager==0) {
   if (act == 7) {
   //2 推荐页主菜单
   returnData.items = yield F.spots(2, returnData.items, {act: act, page: page, version: version, app_ver_arr: Env.app_ver_arr});
   }
   }

   if(act==7 && page==1) { //推荐页增加轮播数据
   //取轮播
   console.log('推荐页轮播');
   var retData = yield F.getSliderNew({title: '', stid: 14, app_ver_arr: fields.app_ver_arr});
   if (!_.isEmpty(retData)) {
   returnData.items.push(retData);
   }
   }
   */

  if (act == 11) {//取得美容日记帖列表
    let dailyThreadArray = [];
    for (let thread of threads) {
      delete thread.ttype;
      delete thread.postusers;
      dailyThreadArray.push(thread);
    }
    var returnDailyData = {
      pageIndex: page,
      items: dailyThreadArray
    };
    return F.returnMsg(200, '成功', 3, returnDailyData)
  }

  if (act == 8 && parseInt(threads[0].fid) == 0 && _.v.isIn(parseInt(threads[0].type), [15, 19])) {
    let postStatus = yield mysql.queryOne('SELECT STATUS from mh_post where tid=? and FIRST=1', [tid]);
    if (postStatus) {
      threads[0].status = parseInt(postStatus['STATUS']);
    }
    threads[0].type = 1;
    if (threads[0].imgcount == 0) {
      threads[0].type = 2;
    }
  }

  if (act == 12) {//act=12返回格式不一样，详见文档（取某个整形日志帖）
    if (threads.length > 0) {
      //判断日记第一篇是否有效，根据post表里面的status判断
      let firstDailyStatus = yield mysql.queryOne('SELECT STATUS from mh_post where tid=? and FIRST=1', [tid]);
      delete threads[0].img;
      delete threads[0].postusers;
      if (threads[0].tags) {
        threads[0].tags = _.filter(threads[0].tags, function (tag) {
          return tag.tagsType == 6;
        });
      }

      for (let thread of threads) {
        delete thread.postusers;
        delete thread.ttype;
        thread.inDaily = 1;
      }
      threads[threads.length - 1].status = parseInt(firstDailyStatus['STATUS']);
      if (!(manager && manager == 1 && F.isManager(loginStatus.groupid))) {
        if (threads[threads.length - 1].status == 0) {
          threads.splice(threads.length - 1, 1);
        }
      }
      else if (firstDailyStatus && threads[threads.length - 1]) {
        delete threads[threads.length - 1].wareName;
        delete threads[threads.length - 1].vendorName;
        delete threads[threads.length - 1].title;
        delete threads[threads.length - 1].wareImageUrl;
        delete threads[threads.length - 1].imageAfter;
        delete threads[threads.length - 1].imageBefore;
        delete threads[threads.length - 1].wareid;

        if (threads[threads.length - 1].tags) {
          threads[threads.length - 1].tags = _.filter(threads[threads.length - 1].tags, function (tag) {
            return tag.tagsType != 6;
          });
        }
      }
    }
  }

  //2015-11-27 如果是推荐跟最新列表，临时处理
  if (fields.app_ver_arr && fields.app_ver_arr.code && fields.app_ver_arr.code < 48) {
    if (_.v.isIn(act, [1, 7])) {
      for (let i in threads) {
        if (!_.v.isIn(threads[i].type, [15, 19])) {
          break;
        } else {
          threads.splice(i, 1);
        }
      }
    }
  }

  // act=8 取某个帖子详情时，判断 manager=1并且是管理人员，则返回新增的1个字段: uliketimes；
  if (act==8 && manager && manager == 1 && F.isManager(loginStatus.groupid)){
    var likedata = yield mysql.queryOne("select liketimes,uliketimes,userreplies from mh_thread where tid=? ",[tid]);
    var liketimes = likedata['liketimes'];
    var uliketimes = likedata['uliketimes'];
    var userreplies = likedata['userreplies'];
    if (parseInt(liketimes) > 0 && parseInt(uliketimes) == 0) {
      //执行初始化计算主贴真实点赞数
      uliketimes = yield F.getUliketimes(liketimes, tid);
      console.log('now uliketimes is %d\n', uliketimes);
      if (parseInt(uliketimes) > 0) {
        //更新数据
        yield mysql.query('UPDATE mh_thread SET uliketimes=? WHERE tid=?', [uliketimes, tid]);
      }
    }
    threads[0]['uliketimes'] = uliketimes;
    threads[0]['userreplies'] =userreplies;
  }

  returnData.items = returnData.items.concat(threads);


  if (act == 8 && fields.addthread == 1 && fields.gain) {
    return F.returnMsg(200, {act: '发帖成功', e: fields.gain}, 4, returnData);
  } else {
    return F.returnMsg(200, '主题列表返回成功', 3, returnData);
  }
};